package com.dongway.core.converter;

import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;

public class MappingJsonpHttpMessageConverter extends FastJsonHttpMessageConverter {

    @Override
    protected void writeInternal(Object o, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
        ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attr.getRequest();
        String jsonpcallback = ServletRequestUtils.getStringParameter(request, "jsonpcallback", null);
        String jsoncallback = ServletRequestUtils.getStringParameter(request, "jsoncallback", null);
        String callback = StringUtils.isNotBlank(jsonpcallback) ? jsonpcallback : jsoncallback;
        if (StringUtils.isNotBlank(callback)) {
            OutputStream out = outputMessage.getBody();
            out.write(callback.getBytes());
            out.write("(".getBytes());
            super.writeInternal(o, outputMessage);
            out.write(")".getBytes());
            out.flush();
        } else {
            super.writeInternal(o, outputMessage);
        }
    }

}
